package com.rw.rule.load;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rw.rule.LoadRule;

/**
 * 简单数据规则，如果存在多个数据源，采用轮询的方式分摊压力
 * 
 * @author lkclkc88(lkclkc88@sina.com)
 * @Date 2016年1月29日
 */
public class SimpleDataSourceRule implements LoadRule {

	private static Logger log = LoggerFactory
			.getLogger(SimpleDataSourceRule.class);

	private int dataSourceSize;

	private AtomicInteger index = new AtomicInteger(0);

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.rw.rule.DataSourceRule#process(java.util.List)
	 */
	public DataSource process(List<DataSource> list) {
		return list.get((index.incrementAndGet() % dataSourceSize));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.rw.rule.DataSourceRule#init(java.util.List)
	 */
	public void initRule(List<DataSource> list) {
		if (null == list || list.size() == 0) {
			if (log.isWarnEnabled()) {
				log.warn("*******  salves dataSource is null ******");
			}
		} else {
			dataSourceSize = list.size();
		}

	}

}
